//
//  HYFStatusPictureView.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/7/25.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

import UIKit

//定义cell 间距
let cellMargin:CGFloat = 5
let cellWH:CGFloat = 80

//重用标识符
private let cellID = "cell"


class HYFStatusPictureView: UICollectionView {

    //声明一个 pictureInfo 模型数组属性
    var pictureInfo:[HYFPictureInfo]?{
        
        didSet{
            
            //给contentLabel赋值
            contentLabel.text = "\(pictureInfo?.count ?? 0)"
            //获得当前的 size 
            let size = getPictureViewSize(pictureInfo?.count ?? 0)
            
            //更新自己的约束
            self.snp_updateConstraints { (make) in
                
                make.size.equalTo(size)
            }
            
            //刷新 UI
            reloadData()
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //获取pictureView 的size
    func getPictureViewSize(count:Int) -> CGSize{
        
        //计算出行数和列数
        let col = count == 4 ? 2 : count >= 3 ? 3 : count
        let row = count == 4 ? 2 : (count - 1)/3 + 1
        
        //计算 size 中的宽和高
        let w = CGFloat(col) * cellWH + CGFloat(col - 1) * cellMargin
        let h = CGFloat(row) * cellWH + CGFloat(row - 1) * cellMargin
        
        return CGSize(width: w, height: h)
    }
    
    //添加视图
    func setupUI(){
        
        backgroundColor = UIColor.clearColor()
        
        //获取layout
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //设置 itemSize
        layout.itemSize = CGSize(width: cellWH, height: cellWH)
        //设置水平和垂直间距
        layout.minimumLineSpacing = cellMargin
        layout.minimumInteritemSpacing = cellMargin
        //注册 cell
        registerClass(HYFStatusPictureViewCell.self, forCellWithReuseIdentifier: cellID)
        //设置数据源代理
        dataSource = self
        delegate = self
        //添加控件
        addSubview(contentLabel)
        //设置约束
        contentLabel.snp_makeConstraints { (make) in
            
           make.center.equalTo(self)
        }
    }
    
    //懒加载contentLabel
    private lazy var contentLabel = UILabel(textColor: UIColor.redColor(), textFont: 35)
    
}


extension HYFStatusPictureView:UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
       return pictureInfo?.count ?? 0
        
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = dequeueReusableCellWithReuseIdentifier(cellID, forIndexPath: indexPath) as! HYFStatusPictureViewCell
        
        cell.backgroundColor = RandomColor()
        
        cell.pic_url = pictureInfo![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        //当前选中图片
        photoBrowser.currentImageIndex = indexPath.item
        //总图数
        photoBrowser.imageCount = pictureInfo!.count
        //父控件
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()
    }
}

extension HYFStatusPictureView:SDPhotoBrowserDelegate{
    
    //小图
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
        let cell = self.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! HYFStatusPictureViewCell
        
        return cell.bgImageView.image
    }
    
    //高清图
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        var urlStr = pictureInfo![index].thumbnail_pic!
        urlStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlStr)
    }
}




class HYFStatusPictureViewCell: UICollectionViewCell {
    
    //定义一个模型,供外界赋值
    var pic_url:HYFPictureInfo?{
        
        didSet{
            
         //给属性赋值
            bgImageView.hyf_setImage(pic_url?.thumbnail_pic, placeholderImgName: "weibo_placeholder")
  
            // 判断是否为nil,考虑 cell 的复用问题
            if let thPic = pic_url?.thumbnail_pic where thPic.hasSuffix(".gif"){
                
                gifImageView.hidden = false
            }else{
                
                gifImageView.hidden = true
            }
        }
    }
    
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI(){
        
        backgroundColor = RandomColor()
       //添加控件
        contentView.addSubview(bgImageView)
        contentView.addSubview(gifImageView)
        //设置约束
        bgImageView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
        gifImageView.snp_makeConstraints { (make) in
            
            make.bottom.equalTo(contentView)
            make.trailing.equalTo(contentView)
        }
    }
    
    //懒加载控件
    private lazy var bgImageView:UIImageView = {
        
       let img = UIImageView(imgName: "weibo_placeholder")
       img.contentMode = .ScaleAspectFill
       img.layer.masksToBounds = true
        
        return img
    }()
    
    //动态图片的logo
    private lazy var gifImageView:UIImageView = UIImageView(imgName: "timeline_image_gif")
    
}


